package com.qilu.pe.ui.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.makeramen.roundedimageview.RoundedImageView;
import com.qilu.pe.R;
import com.qilu.pe.base.BaseResult2;
import com.qilu.pe.base.Global;
import com.qilu.pe.dao.bean.Doctor;
import com.qilu.pe.dao.bean.EventModel;
import com.qilu.pe.dao.bean.Order;
import com.qilu.pe.dao.bean.Patient;
import com.qilu.pe.dao.bean.RefreshEvent;
import com.qilu.pe.dao.http.APIRetrofit;
import com.qilu.pe.support.util.GlideUtil;
import com.qilu.pe.support.util.Logg;
import com.qilu.pe.support.util.PeUtil;
import com.qilu.pe.ui.activity.PatientInfoInputActivity;
import com.ruitu.arad.Arad;
import com.ruitu.arad.api.RxUtil;
import com.ruitu.arad.base.BaseFragment;
import com.ruitu.arad.base.base_list.ListBaseAdapter;
import com.ruitu.arad.base.base_list.SuperViewHolder;
import com.ruitu.arad.util.ToastUtils;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

// 患者选择--我的机构
public class ChoosePatient1Fragment extends BaseFragment implements View.OnClickListener, OnRefreshListener, OnLoadMoreListener {

    private String status;
    private RecyclerView rcv_list;
    private ChoosePatientListAdapter adapter;
    private List<Patient> patientList = new ArrayList<>();

    private SmartRefreshLayout vRefresh;
    private LinearLayout vSearchBar;
    private EditText vName;
    private EditText vPhoneNum;
    private TextView vSearch;
    private int mPage = 1, mPageSize = 15;
    private Doctor mSelfUserInfo;

    public ChoosePatient1Fragment() {

    }

    public static ChoosePatient1Fragment newInstance(String status) {
        ChoosePatient1Fragment fragment = new ChoosePatient1Fragment();
        Bundle args = new Bundle();
        args.putString("status", status);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.status = getArguments().getString("status");
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_choose_patient1, container, false);
        rcv_list = v.findViewById(R.id.rcv_list);

        vRefresh = v.findViewById(R.id.vRefresh);
        View searchBar = LayoutInflater.from(getContext()).inflate(R.layout.layout_patient_search_bar, null, false);
        vSearchBar = searchBar.findViewById(R.id.vSearchBar);
        vName = searchBar.findViewById(R.id.vName);
        vPhoneNum = searchBar.findViewById(R.id.vPhoneNum);
        vSearch = searchBar.findViewById(R.id.vSearch);
        vSearch.setOnClickListener(this);

        adapter = new ChoosePatientListAdapter(patientList);
        adapter.addHeaderView(searchBar);
        LinearLayoutManager manager = new LinearLayoutManager(getActivity());
        rcv_list.setLayoutManager(manager);
        rcv_list.setAdapter(adapter);

        setListeners();

        if ("2".equals(status)) {
            vSearchBar.setVisibility(View.VISIBLE);
        } else {
            vSearchBar.setVisibility(View.GONE);
            vRefresh.autoRefresh();

            APIRetrofit.getDefault().getUserInfo(Global.HEADER, "1")
                    .compose(RxUtil.<BaseResult2<List<Doctor>>>subIoObMain())
                    .subscribe(new Consumer<BaseResult2<List<Doctor>>>() {
                        @Override
                        public void accept(BaseResult2<List<Doctor>> result2) throws Exception {
                            if (result2.isSuccess()) {
                                List<Doctor> doctorList = result2.getData();
                                if (!isDataEmpty(doctorList)) {
                                    mSelfUserInfo = doctorList.get(0);
                                }
                            }
                        }
                    }, new Consumer<Throwable>() {
                        @Override
                        public void accept(Throwable throwable) throws Exception {
                            throwable.printStackTrace();
                        }
                    });
        }

        vRefresh.setOnRefreshListener(this);
        vRefresh.setOnLoadMoreListener(this);
        vRefresh.setEnableLoadMore(false);
        EventBus.getDefault().register(this);
        return v;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.vSearch:
                if (!vName.getText().toString().trim().isEmpty() || !vPhoneNum.getText().toString().trim().isEmpty()) {
                    vRefresh.autoRefresh();
                } else {
                    ToastUtils.showShort("请输入患者姓名或电话");
                }
                break;
        }
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        mPage = 1;
        patientList.clear();
        adapter.notifyDataSetChanged();
        onLoadMore(vRefresh);
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        if ("1".equals(status)) {
            reqPatientListAgent();
        } else {
            if (!vName.getText().toString().trim().isEmpty() || !vPhoneNum.getText().toString().trim().isEmpty()) {
                reqSearchPatientList();
            } else {
                ToastUtils.showShort("请输入患者姓名或电话");
                vRefresh.finishRefresh();
            }
        }
    }

    private void setListeners() {
        adapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                Arad.bus.post(new EventModel(20092351, patientList.get(position)));
                getActivity().finish();
            }
        });
    }

    private Disposable reqPatientListAgent() {
        return APIRetrofit.getDefault().reqPatientListAgent(Global.HEADER, "time")
                .compose(RxUtil.<BaseResult2<List<Patient>>>subIoObMain())
                .subscribe(new Consumer<BaseResult2<List<Patient>>>() {
                    @Override
                    public void accept(BaseResult2<List<Patient>> listBaseResult2) throws Exception {
                        hideProgress();
                        vRefresh.finishRefresh();
                        vRefresh.finishLoadMore();
                        if (listBaseResult2.isSuccess()) {
                            mPage++;
                            patientList.addAll(listBaseResult2.getData());
                            adapter.notifyDataSetChanged();
                        } else {
                            ToastUtils.showShort(listBaseResult2.getMsg());
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                    }
                });
    }

    private Disposable reqSearchPatientList() {
        return APIRetrofit.getDefault().searchPatient(Global.HEADER, vPhoneNum.getText().toString().trim(), vName.getText().toString().trim())
                .compose(RxUtil.<BaseResult2<List<Patient>>>subIoObMain())
                .subscribe(new Consumer<BaseResult2<List<Patient>>>() {
                    @Override
                    public void accept(BaseResult2<List<Patient>> res) throws Exception {
                        hideProgress();
                        vRefresh.finishRefresh();
                        vRefresh.finishLoadMore();
                        if (res.isSuccess()) {
                            mPage++;
                            patientList.addAll(res.getData());
                            adapter.notifyDataSetChanged();
                        } else {
                            ToastUtils.showShort(res.getMsg());
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                    }
                });
    }

    private class ChoosePatientListAdapter extends BaseQuickAdapter<Patient, BaseViewHolder> {

        public ChoosePatientListAdapter(List<Patient> patients) {
            super(R.layout.item_choose_patient_list_1, patients);
        }

        @Override
        protected void convert(BaseViewHolder holder, final Patient patient) {
            TextView tv_name = holder.itemView.findViewById(R.id.tv_name);
            TextView tv_sex = holder.itemView.findViewById(R.id.tv_sex);
            TextView tv_phone = holder.itemView.findViewById(R.id.tv_phone);
            ImageView iv_sex = holder.itemView.findViewById(R.id.iv_sex);
            RoundedImageView iv_header = holder.itemView.findViewById(R.id.iv_header);
            ImageView vEdit = holder.itemView.findViewById(R.id.vEdit);

            tv_name.setText(patient.getName());
            tv_sex.setText(TextUtils.equals("1", patient.getSex()) ? "女" : "男");
            iv_sex.setImageResource(TextUtils.equals("1", patient.getSex()) ?
                    R.mipmap.ic_patient_sex_female : R.mipmap.ic_patient_sex_male);// ic_patient_sex_female ic_patient_sex_male
            tv_phone.setText("电话：" + patient.getPhone());
            GlideUtil.loadImg(PeUtil.getImageUrl(patient.getPicture()), iv_header);
            if ("1".equals(status) && patient.getUid().equals(mSelfUserInfo.getId())) {
                vEdit.setVisibility(View.VISIBLE);
            } else {
                vEdit.setVisibility(View.GONE);
            }

            vEdit.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    startActivity(new Intent(getContext(), PatientInfoInputActivity.class)
                            .putExtra("id", patient.getId())
                            .putExtra("idCard", patient.getIdentity())
                            .putExtra("medical", patient.getMedical())
                    );
                }
            });
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onRefreshEvent(RefreshEvent e) {
        if (e.getAction().equals("patient") && "1".equals(status)) {
            vRefresh.autoRefresh();
        }
    }

    @Override
    public void onDestroyView() {
        EventBus.getDefault().unregister(this);
        super.onDestroyView();
    }
}